import 'package:chat_ai_demo/dao/message_dao.dart';
import 'package:chat_ai_demo/db/db_manage.dart';
import 'package:chat_ai_demo/model/conversation_model.dart';
import 'package:sqflite/sqflite.dart';

abstract class IConversationList {
  Future<int?> saveConversation(ConversationModel model);
  void deleteConversation(ConversationModel model);
  Future<List<ConversationModel>> getConversationList({
    int pageIndex = 1,
    int pageSize = 10,
  });
  Future<void> deleteAllConversations();
}

class ConversationListDao implements IConversationList, ITable {
  final DBManage storage;
  bool _initialized = false;

  ConversationListDao(this.storage);

  Future<void> ensureInitialized() async {
    if (_initialized) return;
    await _initTable();
    _initialized = true;
  }

  Future<void> _initTable() async {
    // 创建新表
    await storage.db.execute('''
      CREATE TABLE IF NOT EXISTS $tableName (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        cid INTEGER NOT NULL,
        title TEXT NOT NULL,
        icon TEXT NOT NULL,
        stickTime INTEGER NOT NULL DEFAULT 0,
        updateAt INTEGER,
        messageCount INTEGER DEFAULT 0,
        lastMessage TEXT
      )
    ''');

    // 创建索引
    await storage.db.execute(
      'create unique index if not exists ${tableName}_cid_index on $tableName (cid);',
    );
  }

  @override
  String tableName = 'tb_conversation_list';

  @override
  Future<void> deleteAllConversations() async {
    await ensureInitialized();
    try {
      final db = storage.db;
      // 开启事务
      await db.transaction((txn) async {
        // 获取所有会话的 cid
        final List<Map<String, dynamic>> conversations = await txn.query(
          tableName,
        );

        // 删除所有会话记录
        await txn.delete(tableName);

        // 删除所有相关的消息表
        for (var conversation in conversations) {
          final messageTableName = MessageDao.tableNameByCid(
            conversation['cid'],
          );
          await txn.execute('DROP TABLE IF EXISTS $messageTableName');
        }
      });
    } catch (e) {
      print('Error deleting all conversations: $e');
      rethrow;
    }
  }

  @override
  Future<void> deleteConversation(ConversationModel model) async {
    await ensureInitialized();
    try {
      final db = storage.db;
      // 开启事务
      await db.transaction((txn) async {
        if (model.id == null) {
          // 删除会话记录
          await txn.delete(tableName, where: 'cid = ?', whereArgs: [model.cid]);
        } else {
          // 删除会话记录
          await txn.delete(tableName, where: 'id = ?', whereArgs: [model.id]);
        }

        // 删除对应的消息表
        final messageTableName = MessageDao.tableNameByCid(model.cid);
        await txn.execute('DROP TABLE IF EXISTS $messageTableName');
      });
    } catch (e) {
      print('Error deleting conversation and messages: $e');
      rethrow;
    }
  }

  @override
  Future<List<ConversationModel>> getConversationList({
    int pageIndex = 1,
    int pageSize = 10,
  }) async {
    await ensureInitialized();
    try {
      final db = storage.db;
      final offset = (pageIndex - 1) * pageSize;

      final List<Map<String, dynamic>> maps = await db.rawQuery(
        'SELECT * FROM $tableName ',
      );
      print('查询$tableName到的会话列表: $maps');
      return maps.map((map) => ConversationModel.fromJson(map)).toList();
    } catch (e) {
      print('Error getting conversation list: $e');
      rethrow;
    }
  }

  @override
  Future<int?> saveConversation(ConversationModel model) async {
    await ensureInitialized();
    try {
      if (model.title == null || model.title!.isEmpty) {
        throw Exception('标题不能为空');
      }

      final db = storage.db;
      // 确保 updateAt 字段有值
      if (model.updateAt == null || model.updateAt == 0) {
        model.updateAt = DateTime.now().millisecondsSinceEpoch;
      }

      print('准备保存会话: ${model.toJson()}');

      // 插入新记录，如果 cid 存在则替换
      final id = await db.insert(
        tableName,
        model.toJson(),
        conflictAlgorithm: ConflictAlgorithm.replace,
      );

      print('会话保存成功，ID: $id');
      model.id = id;
      return id;
    } catch (e) {
      print('Error saving conversation: $e');
      rethrow;
    }
  }
}
